﻿using AutoMapper;
using Infrastructure.Extend;
using Infrastructure.Web;
using MyData.Dto;
using MyData.Models;
using MyDomain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyApplication
{
  public  class HolidayApp
    {
        private IHolidayRepository _service;
        public HolidayApp(IHolidayRepository Service)
        {
            _service = Service;
        }
        public PageDto<HolidayDto> GetHolidays(QueryListModel query, string name)
        {
            var expression = ExtLinq.True<Holiday>();
            if (!string.IsNullOrEmpty(name))
            {
                expression = expression.And(t => t.Name.Contains(name));
            }
            var result = _service.IQueryable(expression).OrderByDescending(t => t.CreatedTime).Paging(query.Limit, query.Offset);
            return new PageDto<HolidayDto>()
            {
                total = result.total,
                rows = Mapper.Map<List<Holiday>, IList<HolidayDto>>(result.rows.ToList())
            };
        }
        public bool SaveHoliday(Holiday holiday)
        {
            if (holiday.Id == Guid.Empty)
            {
                holiday.Id = Guid.NewGuid();
                if (_service.FindEntity(c => c.Name == holiday.Name) != null)
                {
                    throw new KnownException("假期已存在");
                }
                return _service.Insert(holiday) > 0;
            }
            else
            {
                var entity = _service.FindEntity(holiday.Id);
                entity.Name = holiday.Name;
                entity.StartDate = holiday.StartDate;
                entity.EndDate = holiday.EndDate;
                entity.Remark = holiday.Remark;
                return _service.Update(entity) > 0;
            }
        }

        public HolidayDto GetHoliday(Guid Id)
        {
            var entity = _service.FindEntity(Id);
            return Mapper.Map<Holiday, HolidayDto>(entity);
        }
        public Guid? GetHolidayByName(string name)
        {
            var entity = _service.FindEntity(c => c.Name == name);
            return entity?.Id;
        }
        public bool HolidayDelete(Guid Id)
        {
            var entity = _service.FindEntity(Id);
            return _service.Delete(entity) > 0;
        }
        public List<HolidayDto> GetList()
        {
            var result = _service.IQueryable().ToList();
            return Mapper.Map<List<Holiday>, List<HolidayDto>>(result);
        }
    }
}
